import { PipeTransform, Injectable } from '@nestjs/common';
import { PageEnum, SortOrderEnum } from '../dto/paging-query.dto';

export interface PageQueryParam {
  skip: number;
  take: number;
  order: {
    [key: string]: SortOrderEnum;
  };
}

/**
 * @description 分页查询参数管道(实体类需继承CommonEntity)
 */
@Injectable()
export class PaginationPipe implements PipeTransform {
  transform(value: any): PageQueryParam {
    const pageSize = parseInt(value[PageEnum.PAGE_SIZE]);
    const take = pageSize > 0 ? pageSize : 10;
    const pageNum = parseInt(value[PageEnum.PAGE_NUM]);
    const skip = pageNum > 0 ? (pageNum - 1) * take : 0;
    // 默认根据创建时间倒序
    const sortBy = value[PageEnum.SORT_BY] || 'createDate';
    const sortOrder = value[PageEnum.SORT_ORDER] || SortOrderEnum.DESC;
    return {
      skip,
      take,
      order: {
        [sortBy]:
          sortOrder.toLowerCase() === SortOrderEnum.ASC
            ? SortOrderEnum.ASC
            : SortOrderEnum.DESC,
      },
    };
  }
}
